package com.study.myupdate;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.study.myupdate.dialog.LoadingDialog;
import com.study.myupdate.util.DownloadUtil;
import com.study.myupdate.util.LogUtil;
import com.study.myupdate.util.MPermissionUtil;
import com.study.myupdate.util.UpdateUtil;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    //    private String url = "http://new.ztcfb.com/api/app/appInfo.html";
    private String url = "http://39.105.38.67:8088/api/ApkUpdate";
    private LoadingDialog loadingDialog;
    private static final int UPDATE_REQUEST_CODE = 1;
    private String isShow;
    private Button btnDown;
    //    private String downloadUrl = "http://39.105.38.67/CaiJi.apk";
    private String downloadUrl = "https://ec9fb4f6fe95316114e19114179e861e.dlied1.cdntips.net/imtt.dd.qq.com/16891/apk/603074BBFCF112F932711CD401D5CB59.apk";
    //    private String downloadUrl = "http://gdown.baidu.com/data/wisegame/9b6466045d58f370/yingyongbao_7412130.apk";
    private ProgressDialog progressDialog;
    /**
     * app文件的目录
     */
    private String apkPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        loadingDialog = new LoadingDialog(false);

        btnDown = findViewById(R.id.btn_update);

        btnDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goUpdate();
            }
        });

        progressDialog = new ProgressDialog(MainActivity.this);

        apkPath = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + "/download/APK/" + "CaiJi.apk";
    }

    private void goUpdate() {
        // 检查权限然后去更新
        if (MPermissionUtil.checkPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            downloadApp();
        } else {
            MPermissionUtil.requestPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE, UPDATE_REQUEST_CODE);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case UPDATE_REQUEST_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // 得到了权限


                    downloadApp(); // 下载App
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("提示");
                    builder.setMessage("我们需要这个权限来进行文件的读取操作,没有该权限将无法进行此操作，你可以在“设置”——>“权限管理”中找到当前应用，并开启文件读取权限。");
                    builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (isShow != null) {
                                if (isShow.equals("1")) { // 强制更新
                                    Toast.makeText(MainActivity.this, "关闭", Toast.LENGTH_SHORT).show();
                                    finish();
                                }
                            }
                        }
                    });
                    builder.show();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 下载App
     */
    private void downloadApp() {
        if (checkDirApp()) { // 检查目录下是否拥有app,且app是否为最新版本
            updateAPKFroFile();
        } else {
            studyDownload();
        }
    }

    /**
     * 更新apk
     */
    private void updateAPKFroFile() {
        UpdateUtil.installApk(this, apkPath);
    }

    /**
     * 检查更新目录下是否拥有app,且app是否为最新版本
     */
    private boolean checkDirApp() {
        if (isPathExist(apkPath)) { // 文件目录存在
            if (!UpdateUtil.getApkPackageNameFroPath(this, apkPath).equals(getPackageName())) { // 检查包名是否一致
                if (UpdateUtil.getApkVersionCodeFroPath(this, apkPath) >= UpdateUtil.getAppVersion(this)) { // 检查当前的版本号是否一致
                    // 将当前文件夹中的app更新
                    Toast.makeText(this, "更新已有apk", Toast.LENGTH_SHORT).show();
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 检查文件夹中app的版本号
     */
    private void checkDirAppVersion() {

    }

    /**
     * 判断路径是否存在
     *
     * @param path 需要判断的路径
     * @return tru 是存在，false 是不存在
     */
    public static boolean isPathExist(String path) {
        File file = new File(path);
        if (file.exists()) {
            return true;
        }
        return false;
    }

    /**
     * 准备更新
     */
    private void studyDownload() {
        //配置progressDialog
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(true);
        progressDialog.setTitle("正在下载中");
        progressDialog.setMessage("请稍后...");
        progressDialog.setProgress(0);
        progressDialog.setMax(100);
        progressDialog.show();

        goDownload();
    }

    /**
     * 下载APP
     */
    private void goDownload() {
        DownloadUtil.get().download(this, downloadUrl, "APK", "CaiJi.apk", new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                LogUtil.i("下载成功");
                progressDialog.dismiss();

                updateAPKFroFile(); // 安装apk
            }

            @Override
            public void onDownloading(int progress) {
                setDialog(progress);
            }

            @Override
            public void onDownloadFailed() {
                LogUtil.i("下载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "下载失败!", Toast.LENGTH_SHORT).show();
                    }
                });
                progressDialog.dismiss();
            }
        });
    }

    private void setDialog(int progress) {
        progressDialog.setProgress(progress);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 88) {
            UpdateUtil.installApk(this, apkPath);
        }
    }
}
